package device

import (
	"backend/internal/common/errorx"
	"backend/internal/db/model"
	"context"
	"fmt"
	"net/http"

	"backend/internal/svc"
	"backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteDeviceLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeleteDeviceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteDeviceLogic {
	return &DeleteDeviceLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeleteDeviceLogic) DeleteDevice(req *types.DeleteDeviceReq) (resp *types.DeleteDeviceResp, err error) {
	deleteDevice := l.svcCtx.GormDB.Where("name = ?", req.DeviceName).Delete(&model.Device{})
	if deleteDevice.Error != nil {
		errorStr := fmt.Sprintf("删除设备 %v 失败: %v", req.DeviceName, deleteDevice.Error)
		logx.Errorf(errorStr)
		return nil, errorx.NewCodeError(http.StatusInternalServerError, errorStr)
	}

	err = l.svcCtx.ClientManager.DeleteClient(req.DeviceName)
	if err != nil {
		return nil, errorx.NewCodeError(http.StatusBadRequest, fmt.Sprintf("删除设备 %v 失败", req.DeviceName))
	}

	err = l.svcCtx.ClientManager.DeleteClient(req.DeviceName)
	if err != nil {
		return nil, errorx.NewCodeError(http.StatusInternalServerError, fmt.Sprintf("删除设备 %v 失败: 服务器内部错误", req.DeviceName))
	}

	return &types.DeleteDeviceResp{
		Data:   true,
		Msg:    "删除设备成功",
		Status: 200,
	}, nil
}
